#!/bin/bash

sh /opt/init/bootstrap.sh


# 计算堆内存初始大小和限制大小
if [ "x${MEM_REQUEST}" == "x" ]; then
  MEM_REQUEST=700000000
fi
if [ "x${MEM_LIMIT}" == "x" ]; then
  MEM_LIMIT=1000000000
fi
xms=$((700000000*80/100))
xmx=$((${MEM_LIMIT}*70/100))
echo "xms=${xms}"
echo "xmx=${xmx}"


# 计算undertow线程数
if [ "x${CPU_LIMIT}" == "x" ]; then
  # 取不到CPU限制值，则默认看作1.5核
  CPU_LIMIT=1500
fi

if [ $((${CPU_LIMIT})) -lt 1000 ]; then
  # 如果CPU限制值小于1核，则看作1核
  CPU_LIMIT=1000
fi

UNDERTOW_THREADS_IO=$((${CPU_LIMIT}*2/1000))
UNDERTOW_THREADS_WORKER=$((${CPU_LIMIT}*80/1000))

echo "UNDERTOW_THREADS_IO=${UNDERTOW_THREADS_IO}"
echo "UNDERTOW_THREADS_WORKER=${UNDERTOW_THREADS_WORKER}"

# 解开jar包
LIB_PATH=${PROJECT_HOME}/libs
JAR_PATH=${LIB_PATH}/${MAIN_JAR}
mkdir -p ${LIB_PATH}/BOOT-INF/classes/
cp -rf ${PROJECT_HOME}/confs/* ${LIB_PATH}/BOOT-INF/classes/
cd ${LIB_PATH}

# 替换application.yml中的undertow配置
#sed -i "s/#undertow_io#/${UNDERTOW_THREADS_IO}/g" ${LIB_PATH}/BOOT-INF/classes/application.yml
#sed -i "s/#undertow_worker#/${UNDERTOW_THREADS_WORKER}/g" ${LIB_PATH}/BOOT-INF/classes/application.yml

# 将修改后的配置写回jar包
jar uvf ${MAIN_JAR} BOOT-INF/classes/*
rm -rf ${LIB_PATH}/libs/WEB-INF

JAVA_OPTS=" -server -Dfile.encoding=utf-8 -XX:MaxDirectMemorySize=128m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=128m "
JAVA_MEM_OPTS=" -Xms${xms} -Xmx${xmx} -Xss128m -XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap "

echo "exec java ${JAVA_OPTS} ${JAVA_MEM_OPTS} -jar ${JAR_PATH} --spring.profiles.active=test"
if [ "${TIER}" == "prod" ]; then
  exec java ${JAVA_OPTS} ${JAVA_MEM_OPTS} -jar ${JAR_PATH} --spring.profiles.active=test
else
  exec java ${JAVA_OPTS} ${JAVA_MEM_OPTS} -jar ${JAR_PATH} --spring.profiles.active=dev
fi

echo "end..."
~
